<template>
	<view class="body">
		<h2>更换头像</h2>
		<view class="avatarBox">
			<view class="avatar" @click="changeAvatar()">
				<img :src="avatarImg">
			</view>
			<p>点击更换头像</p>
		</view>
		<view @click="uploadImg()">
			<zy-button class="button" :content="buttonContent"></zy-button>
		</view>
		<uni-popup ref="popup" type="message">
		    <uni-popup-message :type="popup.type" :message="popup.message" :duration="popup.duration"></uni-popup-message>
		</uni-popup>
		<uni-popup ref="borad" type="dialog">
		    <uni-popup-dialog type="base" :title="borad.title" :content="borad.message" :duration="2000" :before-close="true" @confirm="confirm" @close="close"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import button from '../components/zy-button.vue'
	export default{
		data(){
			return {
				avatarImg:"",
				buttonContent:"点击更改",
				popup:{
					type:'success',
					message:'成功',
					duration:2000
				},
				borad:{
					title:'',
					message:''
				}
			}
		},
		onLoad(options){
			this.avatarImg = JSON.parse(decodeURIComponent(options.avatarImg));
		},
		components:{
			'zy-button':button
		},
		methods:{
			changeAvatar(){
				uni.chooseImage({
					count:1,
					sourceType: ['album','camera'],
					success:(res)=>{
						console.log(res);
						this.avatarImg = res.tempFilePaths[0];
					}
				})
			},
			async uploadImg(){
				let key = uni.getStorageSync('libilibiUserKey');
				let result = await uni.uploadFile({
					url:this.config.serverUrl+'/uploadImg/changeAvatar',
					name:key.userId,
					filePath:this.avatarImg
				});
				result[1].data = JSON.parse(result[1].data);
				if(result[1].data.status){
					this.popup.type = "success";
					this.popup.message = '成功替换';
					this.$refs.popup.open();
					setTimeout(()=>{
						uni.switchTab({
							url:'./index'
						})
					},2000);
				}
			}
		}
	}
</script>

<style lang="scss">
	.body{
		width:100%;
		height:100vh;
		background-color:rgba(0,0,0,0.75);
		>h2{
			color:white;
			text-align: center;
		}
		>.avatarBox{
			width:100%;
			margin-top:20px;
			display:flex;
			flex-direction: column;
			>.avatar{
				margin:0 auto;
				width:200px;
				height:200px;
				background-color: $zy-libilibi-main;
				border-radius: 200px;
				>img{
					width:200px;
					height:200px;
					border-radius:200px;
				}
			}
			>p{
				margin:10px auto;
				font-size:10px;
				color:white;
				display:block;
			}
		}
		.button{
			width:240px;
			margin:5px auto;
		}
		
	}
</style>
